import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import DashboardView from '../views/DashboardView.vue'
import LoginView from '../views/LoginView.vue'

const routes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/',
    component: HomeView,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        redirect: '/dashboard'
      },
      {
        path: 'dashboard',
        name: 'dashboard',
        component: DashboardView
      },
      {
        path: 'emp',
        name: 'emp',
        component: () => import('../views/emp/emp.vue')
      },
      {
        path: 'dept',
        name: 'dept',
        component: () => import('../views/dept/dept.vue')
      },
      {
        path: 'clue/list',
        name: 'clueList',
        component: () => import('../views/clue/clue-list.vue')
      },
      {
        path: 'clue/pool',
        name: 'cluePool',
        component: () => import('../views/clue/clue-pool.vue')
      },
      {
        path: 'business/list',
        name: 'businessList',
        component: () => import('../views/business/business-list.vue')
      },
      {
        path: 'business/pool',
        name: 'businessPool',
        component: () => import('../views/business/business-public-pool.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 判断路由是否需要认证
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  
  // 检查用户是否已登录
  let isLoggedIn = localStorage.getItem('user') !== null && localStorage.getItem('token') !== null
  
  if (requiresAuth && !isLoggedIn) {
    // 需要登录但未登录，重定向到登录页
    next('/login')
  } else if (to.path === '/login' && isLoggedIn) {
    // 已登录且访问登录页，重定向到首页
    next('/')
  } else {
    // 其他情况，正常跳转
    next()
  }
})

export default router